import os

import cv2
import numpy as np
from PIL import Image
from moviepy.editor import *


def videoBlackWhite(path, outpath):
    clip = VideoFileClip(path)
    clipblackwhite = clip.fx(vfx.blackwhite)
    clipblackwhite.write_videofile(outpath)
    clip.close()


# 按比例拼接、降帧、变黑白
def videoUp(path, path_new, hcount, wcount, fps, jumpstart, jumpend):
    cap = cv2.VideoCapture(path)
    success, _ = cap.read()
    # 分辨率-宽度
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    # 分辨率-高度
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    # 总帧数
    frame_counter = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps_old = int(cap.get(cv2.CAP_PROP_FPS))
    img_size2 = (width * wcount, height * hcount)
    video_writer = cv2.VideoWriter(path_new, cv2.VideoWriter_fourcc(*'mp4v'), fps,
                                   img_size2, True)
    for i in range(jumpstart * fps_old, frame_counter - jumpend * fps_old):
        success, img1 = cap.read()
        try:
            image = Image.fromarray(np.uint8(img1))  # 转换成PIL可以处理的格式
            final_matrix = np.zeros((img_size2[1], img_size2[0], 3), np.uint8)
            for h in range(0, hcount):
                for w in range(0, wcount):
                    final_matrix[height * h:height * (h + 1), width * w:width * (w + 1)] = image
            video_writer.write(final_matrix)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
            print("\r", end="")
            print("进度: {}%: ".format((i - jumpstart * fps_old)*100 / (frame_counter - jumpend * fps_old - jumpstart * fps_old)),
                  "▓" * int((i - jumpstart * fps_old)*100 / (frame_counter - jumpend * fps_old - jumpstart * fps_old)//2),
                  end="")
            sys.stdout.flush()
        except Exception as e:
            print(e)
            break

    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    path = r'D:\bilibilivideobypy\xuya-yaojiwu'
    blackWhitepath = r'D:\bilibilivideobypy\blackWhite\xuya-yaojiwu'
    blackWhitepath_slow = r'D:\bilibilivideobypy\blackWhite\xuya-yaojiwu_slow'
    if not os.path.exists(blackWhitepath):
        os.makedirs(blackWhitepath)
    if not os.path.exists(blackWhitepath_slow):
        os.makedirs(blackWhitepath_slow)
    # for dirpath, dirnames, filenames in os.walk(path):
    #     for filename in filenames:
    #         try:
    #             inputfilename = os.path.join(dirpath, filename)
    #             blackwhitefilepath = os.path.join(blackWhitepath, filename)
    #             print(inputfilename)
    #             videoBlackWhite(inputfilename, blackwhitefilepath)
    #         except Exception as e:
    #             print(e)
    #             continue
    for dirpath, dirnames, filenames in os.walk(blackWhitepath):
        for filename in filenames:
            try:
                inputfilename = os.path.join(dirpath, filename)
                blackwhitefilepath = os.path.join(blackWhitepath_slow, filename)
                print(inputfilename)
                videoUp(inputfilename, blackwhitefilepath, 1, 1, 5, 15, 20)
                print("\r", end="")
            except Exception as e:
                print(e)
                continue
